package net.dotool.thread;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 采集的多线程池
 * @author 李岩飞
 *
 * @param <T>
 */
public final class StatThreadPool<T extends Callable<Object>> {
	public static int DEFAULT_SIZE = 10;
	private ExecutorService services;
	public final List<T> threadRunables;//需要执行的线程

	public StatThreadPool() {
		this(DEFAULT_SIZE);
	}

	public StatThreadPool(final int size) {
		super();
		this.services = Executors.newFixedThreadPool(size);
		this.threadRunables = new Vector<T>(size);
	}

	/**
	 * 创建需要执行的线程
	 * @param threadRunable
	 */
	public void addCallable(final T threadRunable) {
		this.threadRunables.add(threadRunable);
	}

	public void addCallable(final String id, final boolean addThread, final T threadRunable) {
		if (addThread)
			this.threadRunables.add(threadRunable);
	}

	/**
	 * 执行添加的线程
	 */
	public void execute() {
		try {
			this.services.invokeAll(this.threadRunables);
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	/**
	* 执行添加的线程
	*/
	public List<Future<Object>> executeRS() {
		try {
			return this.services.invokeAll(this.threadRunables);
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 执行添加的线程
	 */
	public void executeTimeout(int minute) {
		try {
			this.services.invokeAll(this.threadRunables, minute, TimeUnit.MINUTES);
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行完后清楚 
	 */
	public void executeClear() {
		try {
			this.services.invokeAll(this.threadRunables);
			this.threadRunables.clear();
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	public void shutdown() {
		this.threadRunables.clear();
		this.services.shutdownNow();
	}
}